package service

import (
	"context"
	"fmt"
	"github.com/astaxie/beego/orm"
	"graduation/database"
	"graduation/design"
	"strconv"
)

type RoleService struct {
}

func (r RoleService) UpdateRole(ctx context.Context, msg *design.UpdateRoleRequestMessage) (*design.BaseRespMessage, error) {
	p := []*database.Permission{}
	for _, id := range msg.Permission {
		Id, _ := strconv.Atoi(id)
		p = append(p, &database.Permission{
			Id: Id,
		})
	}
	role := &database.Role{
		Id:   int(msg.Id),
		Name: msg.Name,
	}
	o := orm.NewOrm()
	o.Update(role)
	permissionM2m := o.QueryM2M(role, "Permissions")
	permissionM2m.Clear()
	permissionM2m.Add(p)
	return &design.BaseRespMessage{
		Code: 200,
		Msg:  "修改成功",
	}, nil
}

func (r RoleService) DeleteRole(ctx context.Context, msg *design.BaseRequestMessage) (*design.BaseRespMessage, error) {
	id, _ := strconv.Atoi(msg.Id)
	p := &database.Role{
		Id: id,
	}

	o := orm.NewOrm()
	Rolem2m := o.QueryM2M(p, "Permissions")
	Rolem2m.Clear()
	o.Delete(p)
	o.Commit()
	return &design.BaseRespMessage{
		Code: 200,
		Msg:  "删除成功",
	}, nil
}

func (r RoleService) AddRole(ctx context.Context, msg *design.AddRoleRequestMessage) (*design.BaseRespMessage, error) {

	role := &database.Role{
		Name: msg.Name,
	}
	o := orm.NewOrm()
	o.Insert(role)
	fmt.Println(role)
	roleM2m := o.QueryM2M(role, "Permissions")
	for _, id := range msg.Permission {
		Id, _ := strconv.Atoi(id)
		roleM2m.Add(&database.Permission{
			Id: Id,
		})
		fmt.Println(id)
	}
	o.Commit()
	return &design.BaseRespMessage{
		Code: 200,
		Msg:  "添加成功",
	}, nil
}

func (r RoleService) ListRole(ctx context.Context, msg *design.Empty) (*design.ListRoleResponseMessage, error) {
	results := []*database.Role{}
	o := orm.NewOrm()
	_, error := o.QueryTable("role").All(&results)

	if error != nil {
		return &design.ListRoleResponseMessage{
			Code: 500,
			Msg:  "查询失败",
			List: nil,
			Page: nil,
		}, nil
	}
	data := []*design.UpdateRoleRequestMessage{}
	for _, col := range results {
		o.LoadRelated(col, "Permissions")
		permissions := []string{}
		for _, p := range col.Permissions {
			permissions = append(permissions, strconv.Itoa(p.Id))
		}
		data = append(data, &design.UpdateRoleRequestMessage{
			Id:         int32(col.Id),
			Name:       col.Name,
			Permission: permissions,
		})
	}
	return &design.ListRoleResponseMessage{
		Code: 200,
		Msg:  "获取成功",
		List: data,
		Page: nil,
	}, nil
}
